import { useState, useMemo, useEffect } from 'react'
import {
  Button,
  DatePicker,
  Space,
  Select,
  Card,
  message,
  Typography,
  Modal,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Tooltip,
  List,
} from 'antd'
import {
  CalendarOutlined,
  TableOutlined,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
} from '@ant-design/icons'
import * as XLSX from 'xlsx'
import dayjs from 'dayjs'
import { format, eachDayOfInterval, getDay } from 'date-fns'

const { RangePicker } = DatePicker
const { Option } = Select
const { Text } = Typography

const CalendarExport = ({ data = [] }) => {
  const [exportType, setExportType] = useState('calendar')
  const [dateRange, setDateRange] = useState([
    dayjs().startOf('month'),
    dayjs().endOf('month'),
  ])
  const [exporting, setExporting] = useState(false)

  // 额外工时记录状态
  const [extraWorkTime, setExtraWorkTime] = useState(() => {
    // 从localStorage读取初始数据
    try {
      const saved = localStorage.getItem('extraWorkTime')
      return saved ? JSON.parse(saved) : []
    } catch (error) {
      console.error('读取额外工时数据失败:', error)
      return []
    }
  })
  console.log('extraWorkTime', extraWorkTime)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [currentRecord, setCurrentRecord] = useState(null)
  const [form] = Form.useForm()

  // 监听extraWorkTime变化，自动保存到localStorage
  useEffect(() => {
    try {
      localStorage.setItem('extraWorkTime', JSON.stringify(extraWorkTime))
    } catch (error) {
      console.error('保存额外工时数据失败:', error)
      message.error('数据保存失败，请检查浏览器存储空间')
    }
  }, [extraWorkTime])

  // 额外工时记录相关函数
  const handleAddExtraWork = () => {
    setCurrentRecord(null)
    form.resetFields()
    setIsModalVisible(true)
  }

  const handleEditExtraWork = (record) => {
    setCurrentRecord(record)
    form.setFieldsValue({
      ...record,
      date: record.date ? dayjs(record.date) : dayjs(),
    })
    setIsModalVisible(true)
  }

  const handleDeleteExtraWork = (id) => {
    setExtraWorkTime((prev) => prev.filter((item) => item.id !== id))
    message.success('删除成功')
  }

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields()
      const newRecord = {
        ...values,
        date: values.date ? dayjs(values.date).format('YYYY-MM-DD') : '',
        id: currentRecord ? currentRecord.id : Date.now(),
        createTime: currentRecord
          ? currentRecord.createTime
          : new Date().toLocaleString(),
      }

      if (currentRecord) {
        // 编辑
        setExtraWorkTime((prev) =>
          prev.map((item) => (item.id === currentRecord.id ? newRecord : item))
        )
        message.success('修改成功')
      } else {
        // 新增
        setExtraWorkTime((prev) => [...prev, newRecord])
        message.success('添加成功')
      }

      setIsModalVisible(false)
      form.resetFields()
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  const handleModalCancel = () => {
    setIsModalVisible(false)
    form.resetFields()
    setCurrentRecord(null)
  }

  // 清空所有额外工时记录
  const handleClearAllExtraWork = () => {
    setExtraWorkTime([])
    message.success('已清空所有额外工时记录')
  }

  // 处理日历导出
  const handleCalendarExport = () => {
    if (!dateRange || dateRange.length !== 2) {
      message.error('请选择日期范围')
      return
    }

    setExporting(true)
    try {
      const [startDate, endDate] = dateRange
      const startDay = startDate.toDate()
      const endDay = endDate.toDate()

      // 获取日期范围内的所有日期
      const allDates = eachDayOfInterval({ start: startDay, end: endDay })

      // 创建日历数据结构
      const calendarData = createCalendarData(allDates, data)

      // 导出为Excel
      exportToExcel(
        calendarData,
        `工时日历_${format(startDay, 'yyyy-MM-dd')}_to_${format(
          endDay,
          'yyyy-MM-dd'
        )}.xlsx`
      )

      message.success('日历导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      message.error('导出失败，请重试')
    } finally {
      setExporting(false)
    }
  }

  // 处理表格导出
  const handleTableExport = () => {
    if (!data || data.length === 0) {
      message.error('没有数据可导出')
      return
    }

    setExporting(true)
    try {
      // 过滤并格式化数据
      const filteredData = data.filter((item) => {
        if (!dateRange || dateRange.length !== 2) return true

        const itemDate = dayjs(item.date)
        return (
          itemDate.isAfter(dateRange[0].subtract(1, 'day')) &&
          itemDate.isBefore(dateRange[1].add(1, 'day'))
        )
      })

      const exportData = filteredData.map((item, index) => ({
        序号: index + 1,
        日期: item.date,
        星期: item.weekDay,
        工作内容: item.content,
        '耗时(小时)': item.hours,
        '剩余(小时)': item.remaining,
        对象: item.object,
        产品: item.product,
        执行: item.executor,
        项目: item.project,
      }))

      // 创建工作簿
      const ws = XLSX.utils.json_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '工时记录')

      // 设置列宽
      const colWidths = [
        { wch: 8 }, // 序号
        { wch: 12 }, // 日期
        { wch: 10 }, // 星期
        { wch: 40 }, // 工作内容
        { wch: 12 }, // 耗时
        { wch: 12 }, // 剩余
        { wch: 25 }, // 对象
        { wch: 15 }, // 产品
        { wch: 12 }, // 执行
        { wch: 20 }, // 项目
      ]
      ws['!cols'] = colWidths

      // 导出文件
      const fileName = `工时记录_${format(
        new Date(),
        'yyyy-MM-dd_HH-mm-ss'
      )}.xlsx`
      XLSX.writeFile(wb, fileName)

      message.success('表格导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      message.error('导出失败，请重试')
    } finally {
      setExporting(false)
    }
  }

  // 创建日历数据
  const createCalendarData = (dates, workTimeData) => {
    // 按日期分组工时数据
    const dataByDate = new Map()
    workTimeData.forEach((item) => {
      if (!item.date) return
      if (!dataByDate.has(item.date)) {
        dataByDate.set(item.date, [])
      }
      dataByDate.get(item.date).push(item)
    })

    // 按月份分组日期
    const monthGroups = new Map()
    dates.forEach((date) => {
      const monthKey = format(date, 'yyyy-MM')
      if (!monthGroups.has(monthKey)) {
        monthGroups.set(monthKey, [])
      }
      monthGroups.get(monthKey).push(date)
    })

    const calendarData = []

    // 为每个月创建日历表格
    monthGroups.forEach((monthDates, monthKey) => {
      const monthData = createMonthCalendar(monthDates, dataByDate, monthKey)
      calendarData.push(...monthData)
    })

    return calendarData
  }

  // 创建月度日历
  const createMonthCalendar = (dates, dataByDate, monthKey) => {
    const monthData = []

    // 添加月份标题
    monthData.push({
      月份: monthKey,
      '': '',
      ' ': '',
      '  ': '',
      '   ': '',
      '    ': '',
      '     ': '',
    })

    // 添加星期标题
    monthData.push({
      月份: '日期',
      '': '星期一',
      ' ': '星期二',
      '  ': '星期三',
      '   ': '星期四',
      '    ': '星期五',
      '     ': '星期六',
      '      ': '星期日',
    })

    // 按周分组
    const weeks = []
    let currentWeek = []

    dates.forEach((date) => {
      const dayOfWeek = getDay(date)
      const adjustedDay = dayOfWeek === 0 ? 6 : dayOfWeek - 1 // 调整为周一为0

      // 填充空白日期
      while (currentWeek.length < adjustedDay) {
        currentWeek.push(null)
      }

      currentWeek.push(date)

      // 如果是周日或月末，结束当前周
      if (dayOfWeek === 0 || currentWeek.length === 7) {
        weeks.push([...currentWeek])
        currentWeek = []
      }
    })

    // 添加最后一周
    if (currentWeek.length > 0) {
      while (currentWeek.length < 7) {
        currentWeek.push(null)
      }
      weeks.push(currentWeek)
    }

    // 为每周创建行
    weeks.forEach((week) => {
      const weekRow = {
        月份: '',
        '': '',
        ' ': '',
        '  ': '',
        '   ': '',
        '    ': '',
        '     ': '',
        '      ': '',
      }

      const weekKeys = ['月份', '', ' ', '  ', '   ', '    ', '     ', '      ']

      week.forEach((date, index) => {
        if (date) {
          const dateStr = format(date, 'yyyy-MM-dd')
          const dayData = dataByDate.get(dateStr) || []

          let cellContent = format(date, 'dd')
          if (dayData.length > 0) {
            const totalHours = dayData.reduce(
              (sum, item) => sum + (item.hours || 0),
              0
            )
            cellContent += `\n${totalHours}h`

            // 添加工作内容摘要
            dayData.forEach((item) => {
              const content =
                item.content.length > 20
                  ? item.content.substring(0, 20) + '...'
                  : item.content
              cellContent += `\n${content}`
            })
          }

          weekRow[weekKeys[index]] = cellContent
        }
      })

      monthData.push(weekRow)
    })

    // 添加空行分隔
    monthData.push({
      月份: '',
      '': '',
      ' ': '',
      '  ': '',
      '   ': '',
      '    ': '',
      '     ': '',
      '      ': '',
    })

    return monthData
  }

  // 导出到Excel
  const exportToExcel = (data, filename) => {
    const ws = XLSX.utils.json_to_sheet(data)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '工时日历')

    // 设置列宽
    const colWidths = [
      { wch: 12 }, // 日期/月份
      { wch: 25 }, // 周一
      { wch: 25 }, // 周二
      { wch: 25 }, // 周三
      { wch: 25 }, // 周四
      { wch: 25 }, // 周五
      { wch: 25 }, // 周六
      { wch: 25 }, // 周日
    ]
    ws['!cols'] = colWidths

    XLSX.writeFile(wb, filename)
  }

  // 统计当前筛选范围的数据
  const filteredStats = useMemo(() => {
    if (!dateRange || dateRange.length !== 2) return null

    const filteredData = data.filter((item) => {
      const itemDate = dayjs(item.date)
      return (
        itemDate.isAfter(dateRange[0].subtract(1, 'day')) &&
        itemDate.isBefore(dateRange[1].add(1, 'day'))
      )
    })

    return {
      totalRecords: filteredData.length,
      totalHours: filteredData.reduce(
        (sum, item) => sum + (item.hours || 0),
        0
      ),
      dateRange: `${dateRange[0].format('YYYY-MM-DD')} 至 ${dateRange[1].format(
        'YYYY-MM-DD'
      )}`,
    }
  }, [data, dateRange])

  // 渲染额外工时记录项
  const renderExtraWorkItem = (item) => {
    const title = `${item.content} (${item.hours}h)`
    const description = item.date

    return (
      <List.Item
        actions={[
          <Button
            key='edit'
            type='link'
            size='small'
            icon={<EditOutlined />}
            onClick={() => handleEditExtraWork(item)}
          />,
          <Popconfirm
            key='delete'
            title='确定要删除这条记录吗？'
            onConfirm={() => handleDeleteExtraWork(item.id)}
            okText='确定'
            cancelText='取消'
          >
            <Button type='link' size='small' danger icon={<DeleteOutlined />} />
          </Popconfirm>,
        ]}
      >
        <List.Item.Meta
          title={
            <Tooltip title={title}>
              <div
                style={{
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  maxWidth: '300px',
                }}
              >
                {title}
              </div>
            </Tooltip>
          }
          description={description}
        />
      </List.Item>
    )
  }

  return (
    <div>
      <Card size='small' style={{ marginBottom: '16px' }}>
        <Space direction='vertical' style={{ width: '100%' }}>
          <div
            style={{
              display: 'flex',
              gap: '16px',
              alignItems: 'center',
              flexWrap: 'wrap',
            }}
          >
            <div>
              <Text strong>导出类型：</Text>
              <Select
                value={exportType}
                onChange={setExportType}
                style={{ width: 120, marginLeft: '8px' }}
              >
                <Option value='calendar'>日历格式</Option>
                <Option value='table'>表格格式</Option>
              </Select>
            </div>

            <div>
              <Text strong>日期范围：</Text>
              <RangePicker
                value={dateRange}
                onChange={setDateRange}
                format='YYYY-MM-DD'
                style={{ marginLeft: '8px' }}
              />
            </div>

            <Button
              type='primary'
              icon={
                exportType === 'calendar' ? (
                  <CalendarOutlined />
                ) : (
                  <TableOutlined />
                )
              }
              onClick={
                exportType === 'calendar'
                  ? handleCalendarExport
                  : handleTableExport
              }
              loading={exporting}
              disabled={!data || data.length === 0}
            >
              {exportType === 'calendar' ? '导出日历' : '导出表格'}
            </Button>
          </div>

          {filteredStats && (
            <div
              style={{
                background: '#f9f9f9',
                padding: '12px',
                borderRadius: '4px',
                marginTop: '16px',
              }}
            >
              <Text>
                <strong>导出范围：</strong>
                {filteredStats.dateRange} | <strong>记录数：</strong>
                {filteredStats.totalRecords} 条 | <strong>总工时：</strong>
                {filteredStats.totalHours} 小时
              </Text>
            </div>
          )}
        </Space>
      </Card>

      <div
        style={{
          background: '#f9f9f9',
          padding: '16px',
          borderRadius: '4px',
          fontSize: '14px',
          color: '#666',
        }}
      >
        <h4 style={{ marginBottom: '8px', color: '#333' }}>导出说明：</h4>
        <ul style={{ margin: 0, paddingLeft: '20px' }}>
          <li>
            <strong>日历格式：</strong>
            按月份生成日历表格，每个日期显示当日工时和工作内容摘要
          </li>
          <li>
            <strong>表格格式：</strong>按行显示所有工时记录，包含完整的字段信息
          </li>
          <li>支持自定义日期范围，默认为当前月份</li>
          <li>导出的Excel文件会自动下载到本地</li>
          <li>文件名包含导出类型和日期范围，方便管理</li>
          <li>
            <strong>额外工时记录：</strong>
            数据自动保存到浏览器本地存储，刷新页面不会丢失
          </li>
        </ul>
      </div>

      {/* 额外工时记录 */}
      <Card
        title={
          <span>
            其他记录{' '}
            <small style={{ color: '#3875F6' }}>
              {extraWorkTime.reduce((acc, item) => acc + item.hours, 0)} 小时
            </small>
          </span>
        }
        size='small'
        style={{ marginTop: '16px' }}
        extra={
          <Space>
            <Button
              type='primary'
              size='small'
              icon={<PlusOutlined />}
              onClick={handleAddExtraWork}
            />
            {extraWorkTime.length > 0 && (
              <Popconfirm
                title='确定要清空所有额外工时记录吗？'
                description='此操作不可恢复，请谨慎操作。'
                onConfirm={handleClearAllExtraWork}
                okText='确定'
                cancelText='取消'
              >
                <Button danger size='small' icon={<DeleteOutlined />} />
              </Popconfirm>
            )}
          </Space>
        }
      >
        <List
          dataSource={extraWorkTime}
          renderItem={renderExtraWorkItem}
          size='small'
          pagination={{
            pageSize: 5,
            showSizeChanger: false,
            showQuickJumper: false,
            showTotal: (total) => `共 ${total} 条记录`,
            size: 'small',
          }}
          locale={{
            emptyText: '暂无额外工时记录',
          }}
        />
      </Card>

      {/* 添加/编辑模态框 */}
      <Modal
        title={currentRecord ? '编辑额外工时' : '添加额外工时'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={600}
      >
        <Form
          form={form}
          layout='vertical'
          initialValues={{
            date: dayjs(),
            hours: 0,
          }}
        >
          <Form.Item
            label='日期'
            name='date'
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <DatePicker style={{ width: '100%' }} format='YYYY-MM-DD' />
          </Form.Item>

          <Form.Item
            label='工作内容'
            name='content'
            rules={[{ required: true, message: '请输入工作内容' }]}
          >
            <Input.TextArea rows={3} placeholder='请描述具体的工作内容' />
          </Form.Item>

          <Form.Item
            label='工时(小时)'
            name='hours'
            rules={[
              { required: true, message: '请输入工时' },
              { type: 'number', min: 0, message: '工时不能为负数' },
            ]}
          >
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              step={0.5}
              precision={1}
              placeholder='请输入工时'
            />
          </Form.Item>

          <Form.Item label='备注' name='remark'>
            <Input.TextArea rows={2} placeholder='可选，添加备注信息' />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default CalendarExport
